package org.raymond.iworks.study.netty.atguigu.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Slf4j
public class BioClient {
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket();
        InetSocketAddress socketAddress = new InetSocketAddress(6666);
        log.debug("客户端尝试连接");
        socket.connect(socketAddress); // 建立连接耗费7ms
        log.debug("客户端连接成功");
        //socket.setKeepAlive(true);
        //socket.setSoTimeout(10);
        //Thread.sleep(2000);
        String msg = "12345a";
        OutputStream os = socket.getOutputStream();
        log.info("开始发送数据");
        //Thread.sleep(1000);
        os.write(msg.getBytes(StandardCharsets.UTF_8));
        socket.shutdownOutput();
        log.info("写完第1次");
        //os.write(msg.getBytes(StandardCharsets.UTF_8));
        //log.info("写完第2次");
        //os.close();
        //socket.close();

        //Thread.sleep(10000); // 会影响对端读数据,对端也会等待1000ms,因此在用完后应尽快关闭


        InputStream is = socket.getInputStream();
        log.info("开始接收数据");
        byte[] bytes = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while(true) {
            int read = is.read(bytes);
            if(read>0){
                String str = new String(bytes, StandardCharsets.UTF_8);
                sb.append(str);
            }else{
                break;
            }
        }
        log.info("收到数据:{}", sb);
    }
}
